// Learn cc.Class:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/class.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

const GameDataManger = require("../GameDataManger");

cc.Class({
    extends: cc.Component,

    properties: {
        layoutNode:{    
            default:null,
            type:cc.Node
        },

        sevenItem:{     
            default:null,
            type:cc.Node
        },

    },

    onEnable(){
        this.refresh();
    },

    refresh(){
        for (let index = 0; index < 6; index++) {
            const element = this.layoutNode.children[index];
            if (!element){
                element = cc.instantiate(this.layoutNode.children[0]);
                element.parent = this.layoutNode;
            }
            this.refreshItem(element, index);
        }
        this.refreshItem(this.sevenItem, 6);
    },

    refreshItem(itemNode, index){
        itemNode.getChildByName("dayLab").getComponent(cc.Label).string = "第" + (index+1) + "天";

        itemNode.getChildByName("moneyLab").getComponent(cc.Label).string =  (index+1)*10 + "金币";
        
        itemNode.getChildByName("received").active = GameDataManger.signDay >= index+1;
    },

    btnClick(event,str){
        let day = Number(str);

        if (this.isToday(GameDataManger.signTime)){
            cc.systemEvent.emit(GameDataManger.showTip, "今天已签到");
            return;
        }
        GameDataManger.signDay = day;

        GameDataManger.signTime = Date.now();

        GameDataManger.gold += day*10

        this.refresh();

        cc.systemEvent.emit('saveUserData');
    },

    isToday(timestamp) {
        const date = new Date(timestamp);
        const today = new Date();
        
        return date.getFullYear() === today.getFullYear() && 
               date.getMonth() === today.getMonth() && 
               date.getDate() === today.getDate();
    },

    onDisable(){
    },

    // update (dt) {},
});
